package com.witmore.neutron.ai.mcp.server.trading.controller;

import com.jk.common.response.ResponsePageResult;
import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.mcp.server.trading.controller.dto.StockAlertConfigDTO;
import com.witmore.neutron.ai.mcp.server.trading.dto.*;
import com.witmore.neutron.ai.mcp.server.trading.service.AlertConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 股票异动预警配置API控制器
 * 提供给Web服务调用的REST接口
 *
 * @author 豆子高
 * @since 2025-01-27
 */
@Slf4j
@RestController
@RequestMapping("/api/stock-alert-config")
@Tag(name = "股票预警配置API", description = "提供给其他服务调用的股票异动预警配置接口")
public class StockAlertConfigApiController {

    @Autowired
    private AlertConfigService alertConfigService;

    /**
     * 创建或更新单个股票的异动预警配置
     */
    @PostMapping("/save-or-update")
    @Operation(summary = "保存或更新股票预警配置", description = "根据用户ID和股票代码创建或更新股票异动预警配置")
    public ResponseResult<Boolean> saveOrUpdateStockAlertConfig(@RequestBody StockAlertConfigRequest request) {
        try {
            log.info("接收到股票预警配置请求: userId={}, stockCode={}", request.getUserId(), request.getStockCode());

            // 参数校验
            String validationError = validateStockAlertConfigRequest(request);
            if (validationError != null) {
                log.warn("股票预警配置请求参数校验失败: {}", validationError);
                return ResponseResult.fail(400, validationError);
            }

            // 根据用户ID获取手机号
            String phone = getUserPhoneByUserId(request.getUserId());
            if (phone == null) {
                return ResponseResult.fail(404, "用户不存在或手机号为空");
            }

            // 构建AlertConfigDTO
            AlertConfigDTO alertConfigDTO = buildAlertConfigDTO(request, phone);

            // 调用服务层保存配置
            Boolean result = alertConfigService.saveOrUpdateStockAlertConfig(alertConfigDTO);

            log.info("股票预警配置保存成功: userId={}, stockCode={}, result={}",
                    request.getUserId(), request.getStockCode(), result);

            return ResponseResult.success(result);

        } catch (Exception e) {
            log.error("保存股票预警配置失败: userId={}, stockCode={}",
                    request.getUserId(), request.getStockCode(), e);
            return ResponseResult.fail(500, "保存配置失败: " + e.getMessage());
        }
    }

    /**
     * 批量保存或更新异动预警配置
     */
    @PostMapping("/batch-save-or-update")
    @Operation(summary = "批量保存或更新股票预警配置", description = "批量创建或更新多个股票的异动预警配置")
    public ResponseResult<String> batchSaveOrUpdateAlertConfig(@RequestBody BatchStockAlertConfigRequest request) {
        try {
            log.info("接收到批量股票预警配置请求: userId={}, stockCodes={}",
                    request.getUserId(), request.getStockCodes());

            // 参数校验
            String validationError = validateBatchStockAlertConfigRequest(request);
            if (validationError != null) {
                log.warn("批量股票预警配置请求参数校验失败: {}", validationError);
                return ResponseResult.fail(400, validationError);
            }

            // 根据用户ID获取手机号
            String phone = getUserPhoneByUserId(request.getUserId());
            if (phone == null) {
                return ResponseResult.fail(404, "用户不存在或手机号为空");
            }

            // 构建AlertConfigDTO
            AlertConfigDTO alertConfigDTO = buildBatchAlertConfigDTO(request, phone);

            // 调用服务层保存配置
            String result = alertConfigService.saveOrUpdateAlertConfig(alertConfigDTO);

            log.info("批量股票预警配置保存成功: userId={}, result={}", request.getUserId(), result);

            return ResponseResult.success(result);

        } catch (Exception e) {
            log.error("批量保存股票预警配置失败: userId={}", request.getUserId(), e);
            return ResponseResult.fail(500, "批量保存配置失败: " + e.getMessage());
        }
    }

    /**
     * 删除股票预警配置
     */
    @DeleteMapping("/delete")
    @Operation(summary = "删除股票预警配置", description = "删除指定用户的股票异动预警配置")
    public ResponseResult<String> deleteStockAlertConfig(@RequestParam Long userId, @RequestParam String stockCode) {
        try {
            log.info("接收到删除股票预警配置请求: userId={}, stockCode={}", userId, stockCode);

            // 根据用户ID获取手机号
            String phone = getUserPhoneByUserId(userId);
            if (phone == null) {
                return ResponseResult.fail(404, "用户不存在或手机号为空");
            }

            // 调用服务层删除配置
            String result = alertConfigService.deleteStockAlertConfig(phone, stockCode);

            log.info("删除股票预警配置成功: userId={}, stockCode={}, result={}",
                    userId, stockCode, result);

            return ResponseResult.success(result);

        } catch (Exception e) {
            log.error("删除股票预警配置失败: userId={}, stockCode={}", userId, stockCode, e);
            return ResponseResult.fail(500, "删除配置失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取单个股票预警配置
     */
    @GetMapping("/get/{configId}")
    @Operation(summary = "获取单个股票预警配置", description = "根据配置ID获取股票异动预警配置详情")
    public ResponseResult<StockAlertConfigDTO> getAlertConfigById(@PathVariable Long configId, @RequestParam Long userId) {
        try {
            log.info("接收到获取配置详情请求: configId={}, userId={}", configId, userId);

            // 根据用户ID获取手机号
            String phone = getUserPhoneByUserId(userId);
            if (phone == null) {
                return ResponseResult.fail(404, "用户不存在或手机号为空");
            }

            // 调用服务层获取配置详情
            StockAlertConfigDTO config = alertConfigService.getStockAlertConfigById(userId, configId);

            if (config != null) {
                log.info("获取股票预警配置详情成功: configId={}, userId={}", configId, userId);
                return ResponseResult.success(config);
            } else {
                log.warn("股票预警配置不存在: configId={}, userId={}", configId, userId);
                return ResponseResult.fail(400, "配置不存在或无权限访问");
            }

        } catch (Exception e) {
            log.error("获取股票预警配置详情失败: configId={}, userId={}", configId, userId, e);
            return ResponseResult.fail(500, "获取配置详情失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询股票预警配置
     */
    @PostMapping("/query")
    @Operation(summary = "分页查询股票预警配置", description = "根据条件分页查询用户的股票异动预警配置")
    public ResponsePageResult<StockAlertConfigDTO> queryAlertConfigs(@RequestBody QueryStockAlertConfigRequest request) {
        try {
            log.info("接收到分页查询配置请求: userId={}, page={}, size={}",
                    request.getUserId(), request.getPage(), request.getSize());

            // 参数校验
            String validationError = validateQueryStockAlertConfigRequest(request);
            if (validationError != null) {
                log.warn("分页查询配置请求参数校验失败: {}", validationError);
                return ResponsePageResult.fail(400, validationError);
            }

            // 根据用户ID获取手机号
            String phone = getUserPhoneByUserId(request.getUserId());
            if (phone == null) {
                return ResponsePageResult.fail(404, "用户不存在或手机号为空");
            }

            // 调用服务层分页查询配置
            ResponsePageResult<StockAlertConfigDTO> servicePageResult = alertConfigService.queryStockAlertConfigs(
                    request.getUserId(),
                    request.getStockCode(),
                    request.getStockName(),
                    request.getAlertEnabled(),
                    request.getPage(),
                    request.getSize()
            );

            log.info("分页查询股票预警配置成功: userId={}", request.getUserId());

            // 直接返回服务层的ResponsePageResult
            return servicePageResult;

        } catch (Exception e) {
            log.error("分页查询股票预警配置失败: userId={}", request.getUserId(), e);
            return ResponsePageResult.fail(500, "分页查询失败: " + e.getMessage());
        }
    }


    /**
     * 根据用户ID获取手机号
     */
    private String getUserPhoneByUserId(Long userId) {
        try {
            // 通过用户ID查找用户信息获取手机号
            return alertConfigService.getUserPhoneById(userId);
        } catch (Exception e) {
            log.error("根据用户ID获取手机号失败: userId={}", userId, e);
            return null;
        }
    }

    /**
     * 构建单个股票的AlertConfigDTO
     */
    private AlertConfigDTO buildAlertConfigDTO(StockAlertConfigRequest request, String phone) {
        AlertConfigDTO dto = new AlertConfigDTO();
        dto.setPhone(phone);
        dto.setStockCode(request.getStockCode());
        dto.setRiseRatio(request.getRiseRatio());
        dto.setFallRatio(request.getFallRatio());
        dto.setPushFrequency(request.getPushFrequency());
        dto.setAlertEnabled(request.getAlertEnabled());
        return dto;
    }

    /**
     * 构建批量股票的AlertConfigDTO
     */
    private AlertConfigDTO buildBatchAlertConfigDTO(BatchStockAlertConfigRequest request, String phone) {
        AlertConfigDTO dto = new AlertConfigDTO();
        dto.setPhone(phone);
        dto.setStockCodes(request.getStockCodes());
        dto.setRiseRatio(request.getRiseRatio());
        dto.setFallRatio(request.getFallRatio());
        dto.setPushFrequency(request.getPushFrequency());
        return dto;
    }

    /**
     * 校验股票预警配置请求参数
     */
    private String validateStockAlertConfigRequest(StockAlertConfigRequest request) {
        if (request == null) {
            return "请求参数不能为空";
        }

        if (request.getUserId() == null || request.getUserId() <= 0) {
            return "用户ID不能为空且必须大于0";
        }

        if (request.getStockCode() == null || request.getStockCode().trim().isEmpty()) {
            return "股票代码不能为空";
        }

        if (request.getStockCode().length() > 20) {
            return "股票代码长度不能超过20个字符";
        }

        if (request.getRiseRatio() != null && (request.getRiseRatio().compareTo(java.math.BigDecimal.ZERO) <= 0
                || request.getRiseRatio().compareTo(new java.math.BigDecimal("100")) > 0)) {
            return "上涨预警比例必须在0到100之间";
        }

        if (request.getFallRatio() != null && (request.getFallRatio().compareTo(java.math.BigDecimal.ZERO) <= 0
                || request.getFallRatio().compareTo(new java.math.BigDecimal("100")) > 0)) {
            return "下跌预警比例必须在0到100之间";
        }

        if (request.getPushFrequency() != null && (request.getPushFrequency() < 1 || request.getPushFrequency() > 1440)) {
            return "推送频率必须在1到1440分钟之间";
        }

        return null; // 校验通过
    }

    /**
     * 校验批量股票预警配置请求参数
     */
    private String validateBatchStockAlertConfigRequest(BatchStockAlertConfigRequest request) {
        if (request == null) {
            return "请求参数不能为空";
        }

        if (request.getUserId() == null || request.getUserId() <= 0) {
            return "用户ID不能为空且必须大于0";
        }

        if (request.getStockCodes() == null || request.getStockCodes().trim().isEmpty()) {
            return "股票代码列表不能为空";
        }

        // 校验股票代码格式
        String[] stockCodes = request.getStockCodes().split(",");
        if (stockCodes.length > 50) {
            return "一次最多只能操作50支股票";
        }

        for (String stockCode : stockCodes) {
            if (stockCode.trim().isEmpty() || stockCode.trim().length() > 20) {
                return "股票代码格式错误，每个代码不能为空且长度不能超过20个字符";
            }
        }

        if (request.getRiseRatio() != null && (request.getRiseRatio().compareTo(java.math.BigDecimal.ZERO) <= 0
                || request.getRiseRatio().compareTo(new java.math.BigDecimal("100")) > 0)) {
            return "上涨预警比例必须在0到100之间";
        }

        if (request.getFallRatio() != null && (request.getFallRatio().compareTo(java.math.BigDecimal.ZERO) <= 0
                || request.getFallRatio().compareTo(new java.math.BigDecimal("100")) > 0)) {
            return "下跌预警比例必须在0到100之间";
        }

        if (request.getPushFrequency() != null && (request.getPushFrequency() < 1 || request.getPushFrequency() > 1440)) {
            return "推送频率必须在1到1440分钟之间";
        }

        return null; // 校验通过
    }

    /**
     * 校验分页查询请求参数
     */
    private String validateQueryStockAlertConfigRequest(QueryStockAlertConfigRequest request) {
        if (request == null) {
            return "请求参数不能为空";
        }

        if (request.getUserId() == null || request.getUserId() <= 0) {
            return "用户ID不能为空且必须大于0";
        }

        if (request.getPage() < 1) {
            return "页码必须大于等于1";
        }

        if (request.getSize() < 1 || request.getSize() > 100) {
            return "每页大小必须在1到100之间";
        }

        return null; // 校验通过
    }

}
